<template>
    <div>
        <div id="search">
            <el-form :inline="true" :model="roleSearch" class="demo-form-inline">
                <el-form-item label="角色名">
                    <el-input v-model="roleSearch.roleName" placeholder="请输入角色名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="onSearchSubmit">搜索</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div id="header-bth">
            <el-button type="primary" size="small" icon=el-icon-circle-plus-outline @click="showAddRole">添加</el-button>
        </div>
        <div id="role-table">
            <el-table
                    :data="tableData"
                    stripe
                    style="width: 100%">
                <el-table-column label="角色名">
                    <template slot-scope="scope">
                        <span style="margin-left: 20px">{{ scope.row.roleCh }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="权限字符">
                    <template slot-scope="scope">
                        <span>{{ scope.row.roleEn }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="描述">
                    <template slot-scope="scope">
                        <span>{{ scope.row.comments }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="创建时间" width="150px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.createTime }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="280px">
                    <template slot-scope="scope">
                        <el-button
                                icon="el-icon-edit"
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">
                        </el-button>

                        <el-popconfirm title="确定删除吗？" @confirm="deleteRole(scope.$index, scope.row)">
                            <el-button
                                    slot="reference"
                                    size="mini"
                                    type="danger"
                                    icon="el-icon-delete">
                            </el-button>
                        </el-popconfirm>
                        <el-button
                                size="mini"
                                type="success"
                                @click="handleAuth(scope.$index, scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div id="nav-page">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-sizes="pageSizes"
                    :page-size="roleSearch.limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <!--添加 编辑角色信息弹窗-->
        <el-dialog :title="dialogTitle" :visible.sync="addRoleFormVisible" width="50%" @close="clearInfo">
            <el-form :model="roleForm" ref="roleInfo" :rules="roleRules" label-width="90px" size="medium">
                <el-input v-model="roleForm.roleId" autocomplete="off" v-show="false"></el-input>
                <el-form-item label="角色名" prop="roleCh">
                    <el-input v-model="roleForm.roleCh" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="权限字符" prop="roleEn">
                    <el-input v-model="roleForm.roleEn" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="comments">
                    <el-input v-model="roleForm.comments" show-word-limit maxlength="100" type="textarea"
                              :autosize="{ minRows: 5, maxRows: 10 }" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
            </div>
        </el-dialog>
        <!--分配权限-->
        <el-dialog title="分配权限" :visible.sync="authTreeVisible" width="30%" @close="clearTree">
            <el-tree
                    ref="tree"
                    :data="treeData"
                    show-checkbox
                    node-key="id"
                    :default-checked-keys="defaultCheckedKeys"
                    :default-expand-all="true"
                    :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addRolePermissions">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import {
        addOrUpdateRoleApi,
        addRolePermissionApi,
        deleteRoleByIdApi,
        getAuthTreeApi,
        getRoleByIdApi,
        getRolePageApi, getRolePermissionByRoleIdApi
    } from "@/request/api";
    import {listToTree} from "@/util/treeUtil";

    export default {
        name: "RoleView",
        data() {
            return {
                tableData: [],
                pageSizes: [3, 5, 10, 15],
                total: 10,
                roleId: '',
                addRoleFormVisible: false,
                authTreeVisible: false,
                authTreeCheckedKeys: [],
                defaultCheckedKeys:[],
                dialogTitle: '',
                roleForm: {},
                roleSearch: {  // 搜索数据
                    limit: 3,
                    currentPage: 1
                },
                roleRules: {
                    roleCh: [{required: true, message: '请输入角色名', trigger: 'blur'}],
                    roleEn: [{required: true, message: '请输入角色标识', trigger: 'blur'}]
                },
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                /*权限树形结构数据*/
                treeData: []
            }
        },
        methods: {
            // 编辑角色
            handleEdit(index, row) {
                this.dialogTitle = "编辑角色"
                this.addRoleFormVisible = true
                //  发送异步请求 根据角色id查询角色信息 实现数据回显
                getRoleByIdApi(row.roleId).then(response => {
                    this.roleForm = response.data
                }).catch(error => {
                    this.$message.error("请求失败")
                })
            },
            // 删除角色
            deleteRole(index, row) {
                // 发送异步请求 根据角色id 删除角色信息
                deleteRoleByIdApi(row.roleId).then(response => {
                    if (response.code == 200) {
                        this.$message.success(response.msg)
                        this.list()
                        return
                    }
                    this.$message.warning(response.msg)
                }).catch(error => {
                    this.$message.error("请求失败")
                })
            },
            saveOrUpdate() {
                this.$refs.roleInfo.validate(valid => {
                    if (!valid) {
                        this.$message.warning("请输入必要数据")
                        return
                    }
                    //  发送异步请求   实现角色的添加或修改    roleId
                    addOrUpdateRoleApi(this.roleForm).then(response => {
                        if (response.code == 200) {
                            this.$message.success(response.msg)
                            this.addRoleFormVisible = false
                            this.roleForm = {}
                            this.list()
                            return
                        }
                        this.$message.warning(response.msg)
                    }).catch(error => {
                        this.$message.error("请求失败")
                    })
                })

            },
            /*分配权限*/
            async handleAuth(index, row) {
                // 显示权限分配弹出层
                this.authTreeVisible = true
                this.roleId = row.roleId
                let {data} = await getAuthTreeApi()   // 权限列表
                //遍历返回的权限列表 将数据处理成树形结构需要的样式  [{label:系统管理,id:1,pid:0},{}]
                let permissions = data.map(p => {
                    return {
                        label: p.title,
                        id: p.id,
                        pid: p.pid
                    }
                })
                // 通过工具类将数据挂载成树形结构
                this.treeData = listToTree(permissions)
                // 角色权限数据回显 根据角色id  查询角色的按钮权限
                let {data:btnPermission} =  await getRolePermissionByRoleIdApi(row.roleId)
                this.defaultCheckedKeys = btnPermission
            },
            addRolePermissions() {
                this.authTreeCheckedKeys = [...this.$refs.tree.getHalfCheckedKeys(), ...this.$refs.tree.getCheckedKeys()]
                // 获取角色id
                let roleId = this.roleId;
                let ids = this.authTreeCheckedKeys

                if (ids.length==0){
                    this.$message.warning("请给角色分配权限")
                    return
                }
                // 发送异步请求   添加角色权限
                addRolePermissionApi({roleId,ids}).then(response => {
                    if (response.code == 200) {
                        this.$message.success(response.msg)
                        this.authTreeVisible = false
                        this.defaultCheckedKeys=[]
                        return
                    }
                    this.$message.warning(response.msg)
                }).catch(error => {
                    this.$message.error("请求失败")
                })
            },
            //清空权限回显数据
            clearTree(){
                this.defaultCheckedKeys=[]
            },
            // 搜索角色
            onSearchSubmit() {
                this.roleSearch.currentPage = 1
                this.list()
            },
            // 改变每页显示的条数触发
            handleSizeChange(val) {
                this.roleSearch.limit = val;
                this.list()
            },
            // 改变页码触发
            handleCurrentChange(val) {
                this.roleSearch.currentPage = val;
                this.list()
            },
            // 显示弹出层
            showAddRole() {
                this.dialogTitle = "添加角色"
                this.addRoleFormVisible = true
            },
            //清空校验规则
            clearInfo() {
                this.$refs.roleInfo.clearValidate()
            },
            // 加载角色列表
            list() {
                getRolePageApi(this.roleSearch).then(response => {
                    if (response.code == 200) {
                        this.tableData = response.data.currentPageData
                        this.total = response.data.total
                        return
                    }
                    this.$message.warning(response.msg)
                }).catch(error => {
                    this.$message.error("请求失败")
                })
            }
        },
        created() {
            // 查询角色列表
            this.list()
        }
    }
</script>

<style scoped>
    #search {
        width: 100%;
        height: 50px;
        border-bottom: 1px solid #eee;
    }

    #search, #header-bth, #nav-page {
        margin: 15px;
    }

    #role-table {
        width: 100%;
    }
    .el-button{
        margin-left: 5px;
        margin-right: 5px;
    }
</style>
